//
//  linklist.c
//  线性表链式存储设计与实现
//
//  Created by ZJ on 2018/7/13.
//  Copyright © 2018年 iCatch Technology Inc. All rights reserved.
//

#include "linklist.h"
#include <stdlib.h>
#include <string.h>

typedef struct _tag_LinkList
{
    int length;
    LinkListNode header;
}TLinkList;

LinkList* LinkList_Create(void)
{
    TLinkList *ret = NULL;
    
    ret = (TLinkList *)malloc(sizeof(TLinkList));
    if (ret == NULL) {
        printf("func LinkList_Create() error.\n");
        return NULL;
    }
    
    memset(ret, 0, sizeof(TLinkList));
    
    ret->length = 0;
    ret->header.next = NULL;
    
    return ret;
}

void LinkList_Destroy(LinkList* list)
{
    if (list != NULL) {
        free(list);
        list = NULL;
    }
}

// 让链表恢复到初始状态
void LinkList_Clear(LinkList* list)
{
    TLinkList *tList = NULL;
    
    if (list == NULL) {
        return;
    }
    
    tList = (TLinkList *)list;
    
    tList->length = 0;
    tList->header.next = NULL;
}

int LinkList_Length(LinkList* list)
{
    TLinkList *tList = NULL;
    
    if (list == NULL) {
        return -1;
    }
    
    tList = (TLinkList *)list;
    
    return tList->length;
}

// 指针指向谁就把谁的地址赋给指针
// 分清楚 链表的操作逻辑和辅助指针变量之间的关系
int LinkList_Insert(LinkList* list, LinkListNode* node, int pos)
{
    int ret = 0;
    LinkListNode *current = NULL; //辅助指针变量
    TLinkList *tList = NULL;
    
    if (list == NULL || node == NULL || pos < 0) {
        ret = -1;
        printf("func LinkList_Insert() error: %d\n", ret);
        return ret;
    }
    
    tList = (TLinkList *)list;
    
    current = &(tList->header);
    for (int i = 0; i < pos && (current->next != NULL); i++) {
        current = current->next;
    }
    
    // 1 让node连接后续链表
    node->next = current->next;
    // 2 让前面的链表连接新的node节点
    current->next = node;
    
    tList->length ++;
    
    return ret;
}

LinkListNode* LinkList_Get(LinkList* list, int pos)
{
    LinkListNode *current = NULL;
    TLinkList *tList = NULL;
    
    if (list == NULL || pos < 0) {
        printf("func LinkList_Insert() error.\n");
        return NULL;
    }
    
    tList = (TLinkList *)list;
    
    current = &(tList->header); // 让辅助指针变量指向链表的头部
    
    for (int i = 0; i < pos && (current->next != NULL); i++) { // 跳pos次
        current = current->next;
    }
    
    return current->next;
}

LinkListNode* LinkList_Delete(LinkList* list, int pos)
{
    LinkListNode *current = NULL;
    LinkListNode *ret = NULL;
    TLinkList *tList = NULL;
    
    if (list == NULL || pos < 0) {
        printf("func LinkList_Insert() error.\n");
        return ret;
    }
    
    tList = (TLinkList *)list;
    
    current = &(tList->header); // 让辅助指针变量指向链表的头部
    
    for (int i = 0; i < pos && (current->next != NULL); i++) { // 跳pos次
        current = current->next;
    }
    
    // 缓存被删除的节点位置
    ret = current->next;
    // 连线
    current->next = ret->next;
    tList->length --;
    
    return ret;
}
